<?php
/**
 * Pipahr
 *
 * @author Randy Zhao
 * @copyright 2013 pipahr.com
 */
// JLoader::register("PCompanyHelper", OC::$SERVERROOT."/apps/company/lib/helper.php");
JLoader::register("PJobSeekerModelJobSeeker", OC::$SERVERROOT."/apps/jobseeker/lib/jobseeker.php");
JLoader::register('PInterviewHelper', OC::$SERVERROOT.'/apps/interview/lib/helper.php');
JLoader::register("PMobileHelper", OC::$SERVERROOT."/apps/mobile/lib/helper.php");
JLoader::register("PMobileModelMobile", OC::$SERVERROOT."/apps/mobile/lib/mobile.php");
JLoader::register("PAccountModelAccount", OC::$SERVERROOT."/apps/mobile/lib/account.php");
JLoader::register("PJobModelJob", OC::$SERVERROOT."/apps/mobile/lib/job.php");
JLoader::register("PInterviewModelInterview", OC::$SERVERROOT."/apps/interview/lib/interview.php");
JLoader::register("PPersontestModelPersontest", OC::$SERVERROOT."/apps/interview/lib/persontest.php");

class PMobileController
{
   // Error msg for mobile api
   static $errors = array(
                     '0' => '成功',
                     '10001' => '服务器维护, 请稍后访问',
                     '10002' => '网络错误, 请重试',
                     '10003' => '无效的签名',
                     '10004' => '获取更新信息失败',
                     '20001' => '登录失败',
                     '20002' => '获取用户基本信息失败',
                     '20003' => '访问令牌生成失败',
                     '20004' => '访问令牌认证失败, 请重新登录',
                     '20005' => '用户名或密码错误',
                     '20006' => '您无权访问该资源',
                     '20007' => '用户不存在',
                     '20008' => '当前密码错误',
                     '20009' => '密码和验证密码不一致，请重试',
                     '20010' => '用户绑定设置数据失败',
                     '20011' => '用户保存数据失败',
                     '20012' => '设置登录手机号失败, 请重试',
                     '20013' => '请认真填写反馈',
                     '20014' => '反馈失败, 请重试',
                     '30001' => '获取职位列表失败',
                     '30002' => '职位数为零',
                     '40001' => '无效的邀请码',
                     '40002' => '已完成过线上面试',
                     '40003' => '获取线上笔试题失败',
                     '40004' => '非邀请用户不可参加线上笔试',
                     '40005' => '请先完成线上面试',
                     '40006' => '答题机会已用完',
                     '40007' => '该职位未设置笔试题',
                     '40008' => '已经完成线上笔试',
                     '40009' => '请输入邀请码',
                     '40010' => '此邀请码归属于该登录用户, 无需验证',
                     '40011' => '获取验证信息失败',
                     '40012' => '您的工作经验年限太大了，请认真填写！',
                     '40013' => '请认真填写期望月薪！',
                     '40014' => '请认真填写所有面试题！',
                     '40015' => '新增技能的工作经验（月）格式有误',
                     '40016' => '新增技能的工作经验太大了，请认真填写！',
                     '40017' => '新增技能的熟练度为必选项！',
                     '40018' => '技能经验太大了，请认真填写！',
                     '40019' => '已超过笔试规定时间，提交失败！',
                     '40020' => '请完成您的答卷',
                     '40021' => '出错了, 该公司没有设置笔试题',
                     '40022' => '请输入正确格式的电子邮件',
                     '40023' => '请输入正确的联系电话',
                     '40024' => '验证失败，请核对您简历上提供的信息',
                     '40025' => '获取邀请职位信息失败',
                     '40026' => '获取邀请职位信息成功, 是否要替换主要手机号码?',
                     '40027' => '获取邀请职位信息成功, 是否要用此邮箱替换现有注册邮箱?',
                     '40028' => '邀请验证成功, 已注册用户, 请先登录后再请求该接口',
                     '40029' => '邀请验证成功, 注册失败',
                     '40030' => 'token有效,当前已登录,该邀请码属于当前用户,获取邀请码信息成功,后台对比处理已完成,提示信息参考content中信息,go interview!',
                     '40031' => '该邀请码已被注册, 请先登录后再请求该接口',
                     '40032' => 'email,phone都不存在match, 该邀请码不属于当前用户',
                     '40033' => '已登录状态! 拒绝验证邀请码',
                     '50001' => '参数缺失, 获取性格评测试题失败',
                     '50002' => '您最近做过该性格评测',
                     '50003' => '获取性格评测试题失败',
                     '50004' => '获取性格评测列表失败',
                     '50005' => '获取性格评测结果失败',
                     '60001' => '公司信息获取失败'
                  );

   public static function init() {
      if (false) {
         jexit(jsonError(self::$errors[10001], null, true, 10001));
      }
      $content = array("logo"=>"/images/mobile/init.png");
      jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
   }

   public static function login() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");

      $model = new PAccountModelAccount();

      if ($model->checkAccessToken($access_token, $username)) {
         // Yes token is valid, now check if login session is valid
         if (!OC_User::isLoggedIn()) {
            // Do login, we will check with access_token instead of password
            if (!$model->login()) {
               jexit(jsonError(self::$errors[20005], null, true, 20005));
            }
         }
         // User LoggedIn
         $user = PFactory::getUser();
         $userid = $user->get('id');
         $email = $user->get('email');
         $access_token = $model->setAccessToken($client_id, $userid, $email);
         if (!$access_token) {
            jexit(jsonError(self::$errors[20003], null, true, 20003));
         }

         $userinfo = $model->getJobseekerInfo($userid);
         if (empty($userinfo)) {
            jexit(jsonError(self::$errors[20002], null, true, 20002));
         }

         $content = array_merge($userinfo, $access_token);
         $mobiles = PMobileHelper::getUserMobiles($userid);
         $content['mobiles'] = $mobiles;

         // Success in getting user info.
         jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
      } else {
         // Token not found or not valid, let's do login.
         if (!$model->login()) {
            jexit(jsonError(self::$errors[20005], null, true, 20005));
         }
      }

      if(OC_User::isLoggedIn()) {
         $user = PFactory::getUser();
         $userid = $user->get('id');
         $email = $user->get('email');
         $access_token = $model->setAccessToken($client_id, $userid, $email);
         if (!$access_token) {
            jexit(jsonError(self::$errors[20003], null, true, 20003));
         }

         $userinfo = $model->getJobseekerInfo($userid);
         if (empty($userinfo)) {
            jexit(jsonError(self::$errors[20002], null, true, 20002));
         }

         $content = array_merge($userinfo, $access_token);
         $mobiles = PMobileHelper::getUserMobiles($userid);
         $content['mobiles'] = $mobiles;

         // Success in getting user info.
         jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
      } else {
         // Login failed
         jexit(jsonError(self::$errors[20005], null, true, 20005));
      }
   }

   public static function getjoblist() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $type = JRequest::getString("type","applied"); // received || applied || favorite
      $start = JRequest::getInt("start",0);
      $count = JRequest::getInt("count",10);
      $sort = JRequest::getString("sort","time"); // time || progress

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      $user = PFactory::getUser();
      $userid = $user->get('id');
      $email = $user->get('email');
      $mobiles = PMobileHelper::getUserMobiles($userid);

      $job_model = new PJobModelJob();
      $total = $job_model->getJobListCount($email, $mobiles, $type);
      if ($total <= 0) {
         jexit(jsonError(self::$errors[30002], null, true, 30002));
      }

      $joblist = $job_model->getJobList($email, $mobiles, $userid, $type, $start, $count, $sort);
      if (empty($joblist)) {
         jexit(jsonError(self::$errors[30001], null, true, 30001));
      }

      // Formate data
      $lang = PFactory::getLanguage();
      $lang->load("com_jobs", JPATH_SITE, "zh-CN");
      foreach ($joblist as $k => $j) {
         if (isset($j['online_interview_requirements']) && !empty($j['online_interview_requirements'])) {
            $joblist[$k]['online_interview_requirements'] = json_decode($j['online_interview_requirements'], true);
         }
         if (isset($j['online_interview_progress']) && !empty($j['online_interview_progress'])) {
            $joblist[$k]['online_interview_progress'] = json_decode($j['online_interview_progress'], true);
         }
         if (isset($j['degree_level']) && !empty($j['degree_level'])) {
            $joblist[$k]['degree_level'] = JText::_($j['degree_level']);
         }
         if (isset($j['job_exp']) && !empty($j['job_exp'])) {
            $joblist[$k]['job_exp'] = JText::_($j['job_exp']);
         }
         if (isset($j['employment_type'])) {
            switch ($j['employment_type']) {
               case '0':
                  $joblist[$k]['employment_type'] = "全职";
                  break;
               case '1':
                  $joblist[$k]['employment_type'] = "兼职";
                  break;
               case '2':
                  $joblist[$k]['employment_type'] = "实习";
                  break;
               case '100':
               default:
                  $joblist[$k]['employment_type'] = "不限";
                  break;
            }
         }
      }

      jexit(jsonError(self::$errors[0], array("total"=>intval($total),"list"=>$joblist), true, 0));
   }

   public static function getinterviewlist() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $token = JRequest::getString("token","");
      $start = JRequest::getInt("start",0);
      $count = JRequest::getInt("count",10);

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      // Check invite token
      if ( !PMobileHelper::checkTokenValid($token,$username,$access_token) ) {
         jexit(jsonError(self::$errors[40001], null, true, 40001));
      }

      $interview_model = new PInterviewModelInterview();
      $basicInfo = $interview_model->getInfo($token);

      // Yes token is valid, now check if jobseeker have done interview
      $interviewStat = $interview_model->checkInterviewStat($token);

      // Check if jobseeker have done interview questions before
      if ($interviewStat) {
         jexit(jsonError(self::$errors[40002], null, true, 40002));
      }

      // First time do interview, now get interview list.
      $jobseeker_info = $interview_model->getJobseekerInfo($token);
      $interview_questions = $interview_model->getInterviewQuestions($basicInfo->job_id, true);

      if (empty($interview_questions)) {
         jexit(jsonError(self::$errors[40003], null, true, 40003));
      }

      // Put known value into interview questions
      foreach ($interview_questions as $k => $q) {
         if (isset($q->choices)) {
            $q->choices = json_decode($q->choices);
         }
         switch ($q->alias) {
            case 'SEX':
               if (!empty($jobseeker_info->sex)) {
                  $q->hidden_value = $jobseeker_info->sex;
               }
               break;
            case 'DEGREE':
               if (!empty($jobseeker_info->degree)) {
                  foreach ($q->choices as $key => $value) {
                     if ($jobseeker_info->degree == $value) {
                        $q->hidden_value = $key;
                     }
                  }
               }
               break;
            case 'SCHOOL_LEVEL':
               $q->hidden_value = intval($jobseeker_info->level);
               break;
            case 'AGE':
               if (!empty($jobseeker_info->dateofbirth)) {
                  $q->hidden_value = $jobseeker_info->dateofbirth;
               }
               break;
            case 'LOCATION':
               $q->text_jobseeker = str_ireplace('$city', str_replace('-', '', $q->expected_answer), $q->text_jobseeker);
               break;
            case 'INDUSTRY':
               $q->choices = PMobileHelper::getIndustry();
               break;
         }
         unset($q->expected_answer);
      }

      jexit(jsonError(self::$errors[0], array("total"=>count($interview_questions),"list"=>$interview_questions), true, 0));
   }

   public static function gettestlist() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $token = JRequest::getString("token","");
      $start = JRequest::getInt("start",0);
      $count = JRequest::getInt("count",10);

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      // Check invite token
      if ( !PMobileHelper::checkTokenValid($token,$username,$access_token) ) {
         jexit(jsonError(self::$errors[40001], null, true, 40001));
      }

      // Yes token is valid, forbid un invite token to do onlinetest
      $isInviteToken = PInterviewHelper::isInviteToken($token);
      if (!$isInviteToken) {
         jexit(jsonError(self::$errors[40004], null, true, 40004));
      }

      // Check if jobseeker have done interview questions first.
      $interview_model = new PInterviewModelInterview();
      $interviewStat = $interview_model->checkInterviewStat($token);
      if (!$interviewStat) {
         jexit(jsonError(self::$errors[40005], null, true, 40005));
      }

      if (intval($start) == 0) {
         $qualifications = $interview_model->validateToken($token);
         if (!$qualifications) {
            jexit(jsonError(self::$errors[40006], null, true, 40006));
         }
         // Only update accepted time When getting test question from 0.
         $accepted_stat = $interview_model->updateAccepted($token);
         if (!$accepted_stat) {
            jexit(jsonError(self::$errors[40006], null, true, 40006));
         }
      }

      $basicInfo = $interview_model->getInfo($token);

      $isPaperSet = $interview_model->isPaperSet($token);
      if (!$isPaperSet) {
         jexit(jsonError(self::$errors[40007], null, true, 40007));
      }
      $takenExamBefore = $interview_model->hasTakeExamBefore($token);
      if ($takenExamBefore) {
         jexit(jsonError(self::$errors[40008], null, true, 40008));
      }

      $baseExamInfo = $interview_model->getBaseExamInfo($basicInfo->job_id, $token);
      if (empty($baseExamInfo)) {
         jexit(jsonError(self::$errors[40007], null, true, 40007));
      }


      // Now get test list.
      $examPaper = $interview_model->getExamQuestions($basicInfo->job_id, $baseExamInfo->sheetid, $start, $count, true);

      if (empty($examPaper)) {
         jexit(jsonError(self::$errors[40007], null, true, 40007));
      }

      // Update sheet hits
      PInterviewHelper::updateSheetHits($baseExamInfo->sheetid);

      jexit(jsonError(self::$errors[0], array("sheetid"=>$baseExamInfo->sheetid,"totaltime"=>$baseExamInfo->totaltime,"question_count"=>$baseExamInfo->count,"list"=>$examPaper), true, 0));
   }

   public static function getpersontestlist() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $jobid = JRequest::getInt('jobid', 0);
      $sheetid = JRequest::getInt('sheetid', 0);
      $start = JRequest::getInt("start",0);
      $count = JRequest::getInt("count",10);

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      if(empty($jobid) && empty($sheetid)){
         jexit(jsonError(self::$errors[50001], null, true, 50001));
      }

      $persontest_model = new PPersontestModelPersontest();

      if($jobid){
         $sheetid=$persontest_model->getSheetidByjobid($jobid);
      }

      $hasDone = $persontest_model->hasDone($sheetid);
      $hasDelivered = $persontest_model->hasDelivered($jobid,$sheetid);
      $persontestInfo = $persontest_model->getPersontestInfo($jobid,$sheetid);
      if($hasDone) {
         jexit(jsonError(self::$errors[50002], null, true, 50002));
      }
      if(empty($persontestInfo) || !$hasDelivered) {
         jexit(jsonError(self::$errors[50003], null, true, 50003));
      }

      $persontest_questions = $persontest_model->getPersontestQuestions($jobid,$sheetid,false,$start,$count);
      if (empty($persontest_questions)) {
         jexit(jsonError(self::$errors[50003], null, true, 50003));
      }

      // Save start time on server
      $app = PFactory::getApplication();
      $persontest_start_time = $app->getUserState('persontest_start_time_' . $sheetid, null);
      if(empty($persontest_start_time)) { 
         $persontest_start_time = PFactory::getDate()->toSql();
         $app->setUserState('persontest_start_time_'.$sheetid, $persontest_start_time);
      }

      jexit(jsonError(self::$errors[0], array("sheetid"=>$persontestInfo->sheetid,"alias"=>$persontestInfo->sheetalias,"title"=>$persontestInfo->sheettitle,"description"=>$persontestInfo->description,"totaltime"=>$persontestInfo->totaltime,"question_count"=>$persontestInfo->qcount,"list"=>$persontest_questions), true, 0));
   }

   public static function getallpersontests() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      $user = PFactory::getUser();

      $jseeker_model = new PJobSeekerModelJobSeeker();
      $allpersontests = $jseeker_model->loadjobseekerpersontest();

      if (empty($allpersontests)) {
         jexit(jsonError(self::$errors[50004], null, true, 50004));
      }

      foreach ($allpersontests as $k => $p) {
         $p->icon = "/images/mobile/persontest_".$p->alias.".png";
      }

      jexit(jsonError(self::$errors[0], array("list"=>$allpersontests), true, 0));
   }

   public static function getpersontestresult() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $sheetid = JRequest::getInt('sheetid', 0);

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      $user = PFactory::getUser();
      $jseeker_model = new PJobSeekerModelJobSeeker();

      $persontestResultInfo = $jseeker_model->getjobseekertestResultInfo($sheetid);
      if (empty($persontestResultInfo)) {
         jexit(jsonError(self::$errors[50005], null, true, 50005));
      }

      $persontestResult = $persontestResultInfo->result;
      if (empty($persontestResult)) {
         jexit(jsonError(self::$errors[50005], null, true, 50005));
      }

      $content = array();
      $content['sheet_title'] = $persontestResultInfo->sheetTitle;
      $content['start_time'] = JHtml::_('date', PFactory::getDate($persontestResultInfo->start_time)->toUnix(), 'Y-m-d H:i:s');
      $content['end_time'] = JHtml::_('date', PFactory::getDate($persontestResultInfo->end_time)->toUnix(), 'Y-m-d H:i:s');

      if (empty($persontestResult['result'])) {
         $content['result_title'] = "您的性格特征不明显。";
         $content['result_detail'] = null;
      } else {
         $sheetalias = $persontestResult['alias'];
         $result     = $persontestResult['result'];
         $details    = $persontestResult['details'];

         switch ($sheetalias) {
            default:
            case 'ENNEAGRAM':
            case 'MBTI':
               $persontestAnswer = $jseeker_model->getPersontestAnswer($sheetalias, $result);
               $content['result_title'] = $persontestAnswer->p_title;
               $content['result_detail'] = $persontestAnswer->text;
               break;
            case 'HOLLAND':
               $resultText = '';
               $contesntText = '';
               $strengthText = '';
               $patternArr = str_split($result);
               $hAnswers = $jseeker_model->getPersontestAnswer($sheetalias, $patternArr);
               $aCount = count($hAnswers);
               $find = array('（S）', '（E）', '（C）', '（R）', '（I）', '（A）');

               foreach ($hAnswers as $key => $hAnswer) {
                  $pAlias = $patternArr[$key];
                  $hCount = $details[$pAlias];
                  if ($hCount >= 7 && $hCount <= 10) {
                     $strengthText = '强烈的';
                  } elseif ($hCount >= 4 && $hCount <= 6) {
                     $strengthText = '较明显的';
                  } else {
                     $strengthText = '稍微的';
                  }

                  $resultText .= $strengthText.str_ireplace($find, '', $hAnswer->p_title).'倾向'.($key < ($aCount -1) ? '、' : '');
                  $contesntText .= '<b>'.$hAnswer->p_title.'</b><br/>'.$hAnswer->text;
               }

               $content['result_title'] = $resultText;
               $content['result_detail'] = $contesntText;
               break;
         }
      }

      jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
   }

   public static function postinterview() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $token = JRequest::getString("token","");

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      // Check invite token
      if ( !PMobileHelper::checkTokenValid($token,$username,$access_token) ) {
         jexit(jsonError(self::$errors[40001], null, true, 40001));
      }

      $post = JRequest::get("post");
      if (isset($post['answers'])) {
         $post['answers'] = json_decode($post['answers'],true);
      }

      $interview_model = new PInterviewModelInterview();
      if (!$interview_model->postinterview($post, true)) {
         jexit(jsonError(self::$errors[$interview_model->getErrorCode()], null, true, $interview_model->getErrorCode()));
      }

      jexit(jsonError(self::$errors[0], null, true, 0));
   }

   public static function posttest() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $token = JRequest::getString("token","");

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      // Check invite token
      if ( !PMobileHelper::checkTokenValid($token,$username,$access_token) ) {
         jexit(jsonError(self::$errors[40001], null, true, 40001));
      }

      $post = JRequest::get('post', JREQUEST_ALLOWRAW);
      if (isset($post['answers'])) {
         $post['answers'] = json_decode($post['answers'],true);
      }

      $interview_model = new PInterviewModelInterview();
      $qualifications = $interview_model->validateToken($token);
      if (!$qualifications) {
         jexit(jsonError(self::$errors[40006], null, true, 40006));
      }

      if (!$interview_model->postExam($post,true)) {
         jexit(jsonError(self::$errors[$interview_model->getErrorCode()], null, true, $interview_model->getErrorCode()));
      }

      jexit(jsonError(self::$errors[0], null, true, 0));
   }

   public static function postpersontest() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      $persontest_model = new PPersontestModelPersontest();
      if (!$persontest_model->save(true)) {
         jexit(jsonError(self::$errors[$persontest_model->getErrorCode()], null, true, $persontest_model->getErrorCode()));
      }

      jexit(jsonError(self::$errors[0], null, true, 0));
   }

   public static function getinvitationinfo() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $short_token = JRequest::getString("invite_code",""); // In getinvitationinfo() this token is short token

      if (empty($short_token)) {
         jexit(jsonError(self::$errors[40009], null, true, 40009));
      }

      $token = PInterviewHelper::getLatestToken($short_token,true);
      if (empty($token)) {
         jexit(jsonError(self::$errors[40001], null, true, 40001));
      }

      // So, we are here. This token may not belongs to this user OR the user is currently not logged in.
      // Either way, we need to verify this token.
      // Now get the info we need.
      $interview_model = new PInterviewModelInterview();
      $basicInfo = $interview_model->getInfo($token);
      if (empty($basicInfo)) {
         jexit(jsonError(self::$errors[40011], null, true, 40011));
      }

      $jobseeker_email = $basicInfo->jobseeker_email;
      $jobseeker_phone = $basicInfo->jobseeker_phone;

      $content = array();
      $content['real_token'] = $token;
      $content['jobseeker_name'] = $basicInfo->jobseeker_name;
      $content['comp_name'] = $basicInfo->comp_name;
      $content['job_title'] = $basicInfo->job_title;
      $content['sources'] = $basicInfo->source;
      $content['need_phone'] = starphone($basicInfo->jobseeker_phone);
      if (!isFakeEmail($jobseeker_email)) {
         $content['need_email'] = staremail($jobseeker_email);
      }

      // Check email and phone status
      $account_model = new PAccountModelAccount();
      $is_loggedin = $account_model->checkLogin($username, $access_token);
      $rs_email = JobHelper::getUserByEmail($jobseeker_email);
      $rs_phone = JobHelper::getUserByMobile($jobseeker_phone);

      if (!$is_loggedin) {
         if (!empty($rs_email) && !empty($rs_phone)) {
            jexit(jsonError(self::$errors[40031], array("content"=>$content), true, 40031));
         }

         if (!empty($rs_email)) {
            unset($content['need_phone']);
            jexit(jsonError(self::$errors[40031], array("content"=>$content), true, 40031));
         }

         if (!empty($rs_phone)) {
            unset($content['need_email']);
            jexit(jsonError(self::$errors[40031], array("content"=>$content), true, 40031));
         }
      }

      // We are logged in, do something magic
      if ($is_loggedin) {
         // Get jobdetail for later use
         $job_model = new PJobModelJob();
         $jobdetail = $job_model->getJobDetailByToken($token);
         if (empty($jobdetail)) {
            jexit(jsonError(self::$errors[40025], null, true, 40025));
         }

         // Formate data
         $lang = PFactory::getLanguage();
         $lang->load("com_jobs", JPATH_SITE, "zh-CN");
         foreach ($jobdetail as $key => $value) {
            switch ($key) {
               case 'online_interview_requirements':
                  $jobdetail[$key] = json_decode($value, true);
                  break;
               case 'online_interview_progress':
                  $jobdetail[$key] = json_decode($value, true);
                  break;
               case 'degree_level':
                  $jobdetail[$key] = JText::_($value);
                  break;
               case 'job_exp':
                  $jobdetail[$key] = JText::_($value);
                  break;
            }
         }

         // Do logic
         $user = PFactory::getUser();
         $user_email = $user->email;
         $mobiles = PMobileHelper::getUserMobiles($user->id);

         if ($user_email == $jobseeker_email) {
            if (!in_array($jobseeker_phone, $mobiles)) {
               // Phone not match
               if ( !empty($jobseeker_phone) && !empty($mobiles) ) {
                  // Just add mobile, user can change his primary phone in settings
                  if ($account_model->addNewMobile($user->id,$jobseeker_phone)) {
                     $content['add_new_mobile'] = $jobseeker_phone;
                  }
               } elseif (!empty($jobseeker_phone) && empty($mobiles)) {
                  // Add mobile and set to primary
                  if ($account_model->addNewMobile($user->id,$jobseeker_phone, true)) {
                     $content['set_primary_mobile'] = $jobseeker_phone;
                  }
               }
            }
         } elseif (in_array($jobseeker_phone, $mobiles)) {
            // Email not match
            if ( isFakeEmail($user_email) && !isFakeEmail($jobseeker_email) ) {
               // Auto update user's old fake email, and go interview
               if ( $account_model->updateUserEmail($user, $jobseeker_email) ) {
                  $content['update_login_email'] = $jobseeker_email;
               }
            }
         } else {
            // No matches at all, this token does not belong to login user
            jexit(jsonError(self::$errors[40032], array("content"=>$content), true, 40032));
         }

         $content['jobdetail'] = $jobdetail;
         jexit(jsonError(self::$errors[40030], array("content"=>$content), true, 40030));
      }

      jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
   }

   public static function verifyinvitation() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $token = JRequest::getString("token","");
      $email = JRequest::getString("email","");
      $phone = JRequest::getString("phone","");

      // We are not supposed to be logged in here
      $account_model = new PAccountModelAccount();
      if ($account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[40033], null, true, 40033));
      }

      // Check token valid
      $interview_model = new PInterviewModelInterview();
      $post = JRequest::get('post');
      if (!$interview_model->verifyToken($post,true)) {
         jexit(jsonError(self::$errors[$interview_model->getErrorCode()], null, true, $interview_model->getErrorCode()));
      }

      // Get jobdetail for later use
      $job_model = new PJobModelJob();
      $jobdetail = $job_model->getJobDetailByToken($token);
      if (empty($jobdetail)) {
         jexit(jsonError(self::$errors[40025], null, true, 40025));
      }

      // Formate data
      $lang = PFactory::getLanguage();
      $lang->load("com_jobs", JPATH_SITE, "zh-CN");
      foreach ($jobdetail as $key => $value) {
         switch ($key) {
            case 'online_interview_requirements':
               $jobdetail[$key] = json_decode($value, true);
               break;
            case 'online_interview_progress':
               $jobdetail[$key] = json_decode($value, true);
               break;
            case 'degree_level':
               $jobdetail[$key] = JText::_($value);
               break;
            case 'job_exp':
               $jobdetail[$key] = JText::_($value);
               break;
         }
      }

      // Use email and phone check if registered. if so force user to do login!
      $basicInfo = $interview_model->getInfo($token);
      $jobseeker_email = $basicInfo->jobseeker_email;
      $jobseeker_phone = $basicInfo->jobseeker_phone;

      $rs_email = JobHelper::getUserByEmail($jobseeker_email);
      $rs_phone = JobHelper::getUserByMobile($jobseeker_phone);
      if (!empty($rs_email) || !empty($rs_phone)) {
         // This email or phone has been registered . Force login then do interview
         jexit(jsonError(self::$errors[40028], null, true, 40028));
      }

      // We are here, means token is valid.
      // And email and phone has not been registered before.
      // And user is currently not logged in.
      // Simulate the same way we did in interview APP.
      $app =  PFactory::getApplication();
      $jobseekerinfo = new stdClass;
      $jobseekerinfo->jobseeker_id = $basicInfo->jobseeker_id;
      $jobseekerinfo->jobseeker_name = $basicInfo->jobseeker_name;
      $jobseekerinfo->jobseeker_email = $basicInfo->jobseeker_email;
      $app->setUserState("jobseeker_registers_basicinfo",$jobseekerinfo);
      $app->setUserState("interview_token", $token);
      $app->setUserState("has_verified_token_".$token, true);

      // FIXME: Hack acceptedterms for now
      $_POST['acceptedterms'] = true;

      $jseeker_model = new PJobSeekerModelJobSeeker();
      $jobseeker = $jseeker_model->register(true);
      if (!$jobseeker) {
         // Register failed
         jexit(jsonError(self::$errors[40029], null, true, 40029));
      }

      // Get new reg user info for later use
      $user = PFactory::getUser();
      $userid = $user->get('id');
      $email = $user->get('email');
      $userinfo = $account_model->getJobseekerInfo($userid);
      if (empty($userinfo)) {
         jexit(jsonError(self::$errors[20002], null, true, 20002));
      }

      // Add mobile into db after Joomla Register success.
      if (!empty($jobseeker_phone)) {
         // This is a new user, so we should set this phone number primary too.
         if ($account_model->addNewMobile($userid,$jobseeker_phone,true)) {
            $userinfo['mobiles'] = array($jobseeker_phone);
         }
      }

      // Generate access token
      $new_access_token = $account_model->setAccessToken($client_id, $userid, $email);
      $content['userinfo'] = array_merge($userinfo, $new_access_token);
      $content['jobdetail'] = $jobdetail;

      // Register success, return jobdetail.
      jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
   }

   public static function getcompanyinfo() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $user_id = JRequest::getInt("user_id",0);
      $user = JobHelper::getEmployerProfileDetails($user_id, true);

      if (empty($user)) {
         jexit(jsonError(self::$errors[60001], null, true, 60001));
      }

      $lang = PFactory::getLanguage();
      $lang->load("com_jobs", JPATH_SITE, "zh-CN");

      $content = array();
      $content['user_id'] = $user->user_id;
      $content['industry'] = JText::_($user->industry);
      $content['comp_name'] = $user->comp_name;
      $content['comp_type'] = JText::_($user->comp_type);
      $content['district'] = $user->state.$user->city;
      $content['size_type'] = $user->size_type;
      $content['summary'] = $user->summary;
      $content['validated'] = $user->validated;
      $content['address'] = $user->address;
      $content['website'] = $user->website;
      $content['img_url'] = $user->avatar;

      jexit(jsonError(self::$errors[0], array("content"=>$content), true, 0));
   }

   public static function setpassword() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $username = JRequest::getString("username","");
      $client_id = JRequest::getString("uuid","");
      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      $model = new PJobSeekerModelJobSeeker();
      if(!$model->saveSettings(true)) {
         jexit(jsonError(self::$errors[$model->getErrorCode()], null, true, $model->getErrorCode()));
      }

      // Reset accesstoken
      $user = PFactory::getUser();
      $userid = $user->get('id');
      $email = $user->get('email');
      $access_token = $account_model->setAccessToken($client_id, $userid, $email);

      jexit(jsonError(self::$errors[0], array("content"=>$access_token), true, 0));
   }

   public static function setprimarymobile() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $username = JRequest::getString("username","");
      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";

      // Check login
      $account_model = new PAccountModelAccount();
      if (!$account_model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      $jseeker_model = new PJobSeekerModelJobSeeker();
      if ( !$jseeker_model->setPrimaryMobile(true) ) {
         jexit(jsonError(self::$errors[$jseeker_model->getErrorCode()], null, true, $jseeker_model->getErrorCode()));
      }

      jexit(jsonError(self::$errors[0], null, true, 0));
   }

   public static function feedback() {
      if (!PMobileHelper::checkSignature('post')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $username = JRequest::getString("username","");
      $access_token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : "";
      $type = JRequest::getString("type","feedback");

      // Check login
      $model = new PAccountModelAccount();
      if ($type != "crash" && !$model->checkLogin($username, $access_token)) {
         jexit(jsonError(self::$errors[20001], null, true, 20001));
      }

      if (!$model->postFeedback()) {
         jexit(jsonError(self::$errors[$model->getErrorCode()], null, true, $model->getErrorCode()));
      }

      jexit(jsonError(self::$errors[0], null, true, 0));
   }

   public static function getupdate() {
      if (!PMobileHelper::checkSignature('get')) {
         jexit(jsonError(self::$errors[10003], null, true, 10003));
      }

      $model = new PMobileModelMobile();
      $update = $model->getUpdate();

      if (empty($update)) {
         jexit(jsonError(self::$errors[10004], null, true, 10004));
      }

      jexit(jsonError(self::$errors[0], array('content'=>$update), true, 0));
   }

   public static function token() {
      if (!isDevMode() && !isTestMode()) {
         $from_ip = $_SERVER["REMOTE_ADDR"];
         if ($ip != "153.3.66.123") {
            echo "Access Denied!";
            return false;
         }
      }

      $limit = JRequest::getInt('limit',10);
      $db = PFactory:: getDbo();
      $query = "SELECT a.create_date, a.jobseeker_id, a.short_token, b.email, b.phone
            FROM oc_hr_jobseeker_token a
            LEFT JOIN oc_hr_jobseeker b on b.id = a.jobseeker_id
            WHERE a.short_token > 0 ORDER BY a.create_date DESC LIMIT ".intval($limit);
      $db->setQuery($query);
      $result = $db->loadAssocList();

      if (empty($result)) {
         echo "oooooooooooooooooops!";
         exit;
      }

      foreach ($result as $k => $v) {
         echo "时间: ".$v['create_date'].". || jobseekerid: ".$v['jobseeker_id'].". || 邀请码:".$v['short_token'].". || email: ".$v['email'].". || phone: ".$v['phone'];
         echo "<br>";
      }
   }
}
